package cn.tedu.csmall.sso.config;


import cn.tedu.csmall.sso.filter.JwtAuthorizationFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@Slf4j
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启基于方法的安全检查
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    JwtAuthorizationFilter jwtAuthorizationFilter;

    @Bean
    public PasswordEncoder passwordEncoder(){
        log.info("创建密码加密组件");
        return new BCryptPasswordEncoder();
    }


    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    //配置默认放行
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //如果没有这行代码导致用户无法被认证。这行代码的含义是：关闭csrf防护。
        ////关闭csrf防护
        http.csrf().disable();

        //配置初始放行的白名单
        String[] urls={
                "/admins/login",
                "/doc.html",
                "/**/*.css",
                "/**/*.js",
                "/favicon.ico",
                "/v2/api-docs",
                "/swagger-resources"
        };
        http.authorizeRequests() //设置请求的权限
                .antMatchers(urls)//匹配什么路径  所有路径
                //允许访问（不需要经过认证和授权）
                .permitAll()
                // 除了以上配置过的其它任何请求
                .anyRequest()
                // 已经通过认证，即已经登录过才可以访问
                .authenticated();


        // 添加处理JWT的过滤器，必须执行在处理用户名、密码的过滤器（Spring Security内置）之前
        http.addFilterBefore(jwtAuthorizationFilter,UsernamePasswordAuthenticationFilter.class);

    }


}
